package com.ruoyi.student_club.utils;

import com.ruoyi.common.utils.uuid.UUID;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * @Author lin
 * @Date 2022/1/20 14:50
 */
public class UploadUtil {

    public static String upload(MultipartFile file, String typeName) {
        //获取原文件名
        String fileName = file.getOriginalFilename();
        //获取后缀名
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        //可拦截后缀名，先不加判断
        //去掉后缀
        fileName = fileName.substring(0, fileName.indexOf("."));
        //唯一串
        String uuid = UUID.randomUUID().toString().replace("-", "");
        //新文件名
        String newFileName = uuid + suffix;
        String url = null;
        try {
            url = ResourceUtils.getURL("classpath:").getPath();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        String path = url + "static/upload/"+ typeName +"/" + newFileName;
        File image = new File(path);
        if (!image.exists() && !image.isDirectory()) {
            image.getParentFile().mkdirs();
        }
        try {
            file.transferTo(image);
        } catch (IOException e) {
            throw new RuntimeException("上传图片失败！" + e.getMessage());
        }
        return path;
    }

    public static void deletePicture(String path) {
        File file = new File(path);
        file.delete();
    }
}
